package com.cykj.user.utils;

import com.alibaba.druid.util.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

@Component
public class SensitiveWordUtils {
    private Set<String> sensitiveWords = new HashSet<>();
    private boolean initSuccess = false;

    @PostConstruct
    public void init() {
        try {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:static/Vocabulary/*.txt");

            for (Resource resource : resources) {
                try (InputStream is = resource.getInputStream();
                     BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (!line.trim().isEmpty()) {
                            sensitiveWords.add(line.trim());
                        }
                    }
                }
            }
            initSuccess = true;
            System.out.println("成功加载敏感词数量: " + sensitiveWords.size());
        } catch (Exception e) {
            System.err.println("敏感词初始化失败: " + e.getMessage());
            initSuccess = false;
        }
    }

    public boolean containsSensitiveWord(String text) {
        if (!initSuccess || StringUtils.isEmpty(text)) {
            return false;
        }
        return sensitiveWords.stream().anyMatch(text::contains);
    }

    public String validateUsername(String username) {
        if (!initSuccess) {
            if (username.length() < 2 || username.length() > 16) {
                return "用户名长度需在2-16个字符之间";
            }
            return null;
        }

        if (containsSensitiveWord(username)) {
            return "用户名包含敏感词，请修改";
        }
        if (username.length() < 2 || username.length() > 16) {
            return "用户名长度需在2-16个字符之间";
        }
        return null;
    }
}
